package com.lk.client.rpc.handler;

import com.lk.entity.PingMessage;
import com.lk.entity.PongMessage;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 客户端的心跳handler
 */
@Slf4j
public class HeartBeatClientHandler extends SimpleChannelInboundHandler<PongMessage> {

    /**
     * idlStatus写事件
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            switch (idleStateEvent.state()) {
                case READER_IDLE:
                    //长时间没有写入数据  发送心跳包
                    //获取ip
                    log.info("发送心跳包 {}", ctx.channel().remoteAddress());
                    PingMessage message = new PingMessage();
                    message.setPing("ping");
                    ctx.writeAndFlush(message);
                    break;

            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.debug("远程调用出错");
        cause.printStackTrace();
        ctx.close();
        super.exceptionCaught(ctx, cause);
    }


    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelUnregistered");
        ctx.close();
        super.channelUnregistered(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PongMessage msg) throws Exception {
        log.info("pong:{}", msg);
    }
}
